package com.eam.handler;

import com.basis.utils.CodeGenerateRuleUtil;
import com.eam.data.EamMaintainPlan;
import com.eam.data.EamMaintainPlanFacs;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.service.OBDal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备维保计划
 * @author Administrator
 */
public class GeneratePlanHandler extends BaseActionHandler {

	public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject jsonRep = new JSONObject();

		try {
			JSONObject reqData = new JSONObject(content);
			String message = "";
			String type = reqData.getString("type");

			// 勾选设备生成计划
			if (type.equalsIgnoreCase("GENERATE_PLAN")) {
				String jsonIds = reqData.getString("ids");
				String[] ids = jsonIds.split("#####");
				EamMaintainPlan emp = createMaintainPlan();
				int i = 0;
				for (String id : ids) {
					
					EamMaintainPlanFacs empi = OBDal.getInstance().get(EamMaintainPlanFacs.class, id);
					i += 1;

					if (empi.getUser() == null) {
						message += "【设备：" + empi.getEamFacilities().getName() + "，未指定责任人，请仔细检查】<br/>";
						continue;
					}

					
					if (message.equalsIgnoreCase("")) {
						empi.setEamMaintainPlan(emp);
						empi.setStatus("UNAPPROVED");
						OBDal.getInstance().save(empi);
					}
				}
				if (message.equalsIgnoreCase("")) {
					jsonRep.put("result", true);
					jsonRep.put("message", "计划申报成功，请等待处理管理员确认");
					OBDal.getInstance().commitAndClose();
					return jsonRep;
				} else {
					jsonRep.put("result", false);
					jsonRep.put("message", message);
					OBDal.getInstance().rollbackAndClose();
					return jsonRep;
				}
			}
			
			
			
			
			// 审核保养计划
			if (type.equalsIgnoreCase("AUDIT")) {
				String jsonIds = reqData.getString("ids");
				JSONObject data = auditPlan(jsonIds);
				if (data.getBoolean("result")) {
					jsonRep.put("result", true);
					jsonRep.put("message", "计划审核成功。");
					OBDal.getInstance().commitAndClose();
				} else {
					jsonRep.put("result", false);
					jsonRep.put("message", data.getString("message"));
					OBDal.getInstance().rollbackAndClose();
				}
				return jsonRep;
			}
			
			// 审核维修计划
			if (type.equalsIgnoreCase("CHECK")) {
				String jsonIds = reqData.getString("ids");
				JSONObject data = auditCheckPlan(jsonIds);
				if (data.getBoolean("result")) {
					jsonRep.put("result", true);
					jsonRep.put("message", "计划审核成功。");
					OBDal.getInstance().commitAndClose();
				} else {
					jsonRep.put("result", false);
					jsonRep.put("message", data.getString("message"));
					OBDal.getInstance().rollbackAndClose();
				}
				return jsonRep;
			}

		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			try {
				jsonRep.put("result", false);
				jsonRep.put("message", "处理失败");
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

		return jsonRep;
	}

	/**
	 * 生成计划头信息
	 * 
	 * @return
	 */
	protected EamMaintainPlan createMaintainPlan() throws Exception {
		EamMaintainPlan emp = new EamMaintainPlan();
		String code = CodeGenerateRuleUtil.getCode("95C2F9476DCD45CF90BAB1FC79E2F4FB", "Code");
		emp.setName(getQquence());
		emp.setCode(code);
		emp.setStatus("UNAPPROVED");
		emp.setStartDate(new Date());
		OBDal.getInstance().save(emp);
		return emp;
	}

	/**
	 * 获取squence
	 * 
	 * @return
	 */
	protected String getQquence() {
		Date date = new Date();
		String squence = sdf.format(date);
		squence = squence.replace("-", "").replace(" ", "").replace(":", "");
		return squence.substring(2, 10);
	}

	/**
	 * 更新保养计划状态，将待审核更新为已审核
	 * 
	 * @param ids
	 * @return
	 * @throws JSONException
	 */
	protected JSONObject auditPlan(String ids) throws JSONException {
		JSONObject response = new JSONObject();
		String message = "";
		boolean flag = true;
		String[] idsArg = ids.split("#####");
		List<EamMaintainPlanFacs> list = new ArrayList<EamMaintainPlanFacs>();

		response.put("result", true);

		for (String id : idsArg) {
			EamMaintainPlan emp = OBDal.getInstance().get(EamMaintainPlan.class, id);

			if (emp.getStatus().equalsIgnoreCase("UNAPPROVED")) {
				emp.setStatus("OK");
				OBDal.getInstance().save(emp);
			} else {
				flag = false;
				message += "【保养计划：" + emp.getName() + "，不是待审核状态，无法更新】</br>";
				continue;
			}

			if (!flag) {
				continue;
			}

		}

		if (message != "") {
			response.put("result", false);
			response.put("message", message);
		}
		return response;
	}
	
	/**
	 * 更新维修计划状态，将待审核更新为已审核
	 * 
	 * @param ids
	 * @return
	 * @throws JSONException
	 */
	protected JSONObject auditCheckPlan(String ids) throws JSONException {
		JSONObject response = new JSONObject();

	try{	
		String message = "";
		boolean flag = true;
		String[] idsArg = ids.split("#####");
		List<EamMaintainPlanFacs> list = new ArrayList<EamMaintainPlanFacs>();

		response.put("result", true);
		
		
			//获取当前系统时间并存入维修开始里面（由审核按钮控制）
			//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			//java.util.Date time = sdf.parse(sdf.format(new Date()));
			
		
		
		for (String id : idsArg) {
			EamMaintainPlan emp = OBDal.getInstance().get(EamMaintainPlan.class, id);

			if (emp.getStatus().equalsIgnoreCase("UNAPPROVED")) {
				emp.setStatus("APPROVED");
				//emp.setStartDate(time);
				OBDal.getInstance().save(emp);
			} else {
				flag = false;
				message += "【维修计划：" + emp.getName() + "，不是待审核状态，无法更新】</br>";
				continue;
			}

			if (!flag) {
				continue;
			}

			list = emp.getEamMaintainPlanFacsList();
			for (EamMaintainPlanFacs obj : list) {
				obj.setStatus("APPROVED");
				OBDal.getInstance().save(obj);
			}
		}

		if (message != "") {
			response.put("result", false);
			response.put("message", message);
		}
	}catch(Exception e){
		e.printStackTrace();
	}
		return response;
	}
}
